package com.yuantong.xyerp.rest.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.yuantong.xyerp.core.api.dto.ContractDto;
import com.yuantong.xyerp.core.api.dto.WarehouseReceiptListDto;
import com.yuantong.xyerp.core.api.dto.WarehouseRecordsDto;
import com.yuantong.xyerp.core.api.form.QueryForm;
import com.yuantong.xyerp.core.provider.dao.WarehouseReceiptListMapper;
import com.yuantong.xyerp.core.provider.dao.WarehouseRecordsMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Jianguo.Yin on 2021-08-06.
 */
@Api(tags = "库存管理")
public class WarehouseController {
    @Resource
    private WarehouseRecordsMapper warehouseRecordsMapper;
    @Resource
    private WarehouseReceiptListMapper warehouseReceiptListMapper;
    //todo: 需要关联什么表?

    private Map<String, ExcelExportEntity> getWarehouseContractColumns() {
        Map<String, ExcelExportEntity> warehouseContractColumns = new HashMap<>();


        ExcelExportEntity exportEntity = new ExcelExportEntity("产品类型", "type",40);
        exportEntity.setReplace(new String[]{"原料_0","成品_1"});

        ExcelExportEntity exportEntity2 = new ExcelExportEntity("提交时间", "createTime", 40);
        exportEntity2.setFormat("yyyy-MM-dd hh:mm");

        ExcelExportEntity exportEntity3 = new ExcelExportEntity("类型", "type", 40);
        exportEntity3.setReplace(new String[]{"采购入库_1","生产产品入库_2","调拨入库_3","退货入库_4","销售出库_5","调拨出库_6","生产原料出库_7"});


        // 库存查询导出
        warehouseContractColumns.put("一级别品名",new ExcelExportEntity("一级别品名", "levelOne", 40));
        warehouseContractColumns.put("二级别品名",new ExcelExportEntity("二级别品名", "levelTwo", 40));
        warehouseContractColumns.put("货品名称",new ExcelExportEntity("货品名称", "goodsName", 40));
        warehouseContractColumns.put("品类",new ExcelExportEntity("品类", "categoryName", 40));
        warehouseContractColumns.put("产品类型",exportEntity);
        warehouseContractColumns.put("所在仓库",new ExcelExportEntity("所在仓库", "warehouseName", 40));
        warehouseContractColumns.put("库存总量（吨）",new ExcelExportEntity("库存总量（吨）", "weight", 40));
        // 库存查询导出
        warehouseContractColumns.put("提交时间",exportEntity2);
        warehouseContractColumns.put("单据编号",new ExcelExportEntity("单据编号", "docNo", 40));
        warehouseContractColumns.put("关联业务单号",new ExcelExportEntity("关联业务单号", "contractNo", 40));
        warehouseContractColumns.put("类型",exportEntity3);
        warehouseContractColumns.put("重量（吨）",new ExcelExportEntity("重量（吨）", "totalWeight", 40));



        return warehouseContractColumns;
    }

    /**
     * 库存查询导出
     */
    @ApiOperation(value = "库存查询导出",httpMethod = "POST", produces = "application/octet-stream")
    @PostMapping(value = "/export/warehouse_list", produces = "application/octet-stream;charset=utf-8")
    public void warehouseList(HttpServletResponse response,
                             HttpServletRequest request,
                             @ApiParam("查询参数") @RequestBody QueryForm queryForm) {

        List<ExcelExportEntity> entity = new ArrayList<>();
        Map<String, ExcelExportEntity> map = getWarehouseContractColumns();

        entity.add(map.get("一级别品名"));
        entity.add(map.get("二级别品名"));
        entity.add(map.get("货品名称"));
        entity.add(map.get("品类"));
        entity.add(map.get("产品类型"));
        entity.add(map.get("所在仓库"));
        entity.add(map.get("库存总量（吨）"));

        List<WarehouseRecordsDto> list = warehouseRecordsMapper.findAllByFuzzy(queryForm.getFuzzy(), queryForm.getIds());

        String fileName = "库存查询导出列表";
        Workbook workbook = ExcelExportUtil
                .exportExcel(new ExportParams(fileName, fileName, ExcelType.HSSF), entity, list);

        ServletOutputStream outputStream = null;
        try {
            response.setContentType("application/octet-stream");
            //中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 库存流水
     */
    @ApiOperation(value = "库存流水导出",httpMethod = "POST", produces = "application/octet-stream")
    @PostMapping(value = "/export/warehouse_flow", produces = "application/octet-stream;charset=utf-8")
    public void warehouseFlow(HttpServletResponse response,
                             HttpServletRequest request,
                             @ApiParam("查询参数") @RequestBody QueryForm queryForm) {

        List<ExcelExportEntity> entity = new ArrayList<>();
        Map<String, ExcelExportEntity> map = getWarehouseContractColumns();

        entity.add(map.get("提交时间"));
        entity.add(map.get("单据编号"));
        entity.add(map.get("关联业务单号"));
        entity.add(map.get("品类"));
        entity.add(map.get("类型"));
        entity.add(map.get("重量（吨）"));

        List<WarehouseReceiptListDto> list = warehouseReceiptListMapper.findAllByFuzzy(queryForm.getWarehouseReceiptId(),queryForm.getFuzzy(), queryForm.getWarehouseReceiptType(),null);

        String fileName = "库存流水导出列表";
        Workbook workbook = ExcelExportUtil
                .exportExcel(new ExportParams(fileName, fileName, ExcelType.HSSF), entity, list);

        ServletOutputStream outputStream = null;
        try {
            response.setContentType("application/octet-stream");
            //中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
